package com.tegistuff.webos.util;

import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.tegistuff.webos.run.WebOSRunConfiguration;

/**
 * WebOSFileMapper.java
 *
 * Copyright (C) 2011-2012 Timo Tegtmeier.
 * All rights reserved.
 */
public class WebOSFileMapper {
    
    private static String WEBOS_LOCAL_FILE_PREFIX = "file://";
    private static String WEBOS_APP_BASE_PATH = WEBOS_LOCAL_FILE_PREFIX + "/media/cryptofs/apps/usr/palm/";
    private static String WEBOS_APP_FOLDER = WEBOS_APP_BASE_PATH + "applications/";
    private static String WEBOS_SERVICE_FOLDER = WEBOS_APP_BASE_PATH + "services";
    
    public static String MapPathToWebOS(WebOSRunConfiguration configuration, String path) {
        if(isFileOf(path, configuration.getAppFolder()))
            return getWebOSPath(WEBOS_APP_FOLDER, configuration, path, configuration.getAppFolder());
        if(isFileOf(path, configuration.getSrvFolder()))
            return getWebOSPath(WEBOS_SERVICE_FOLDER, configuration, path, configuration.getSrvFolder());
        return null;
    }
    
    public static VirtualFile MapToLocalFile(WebOSRunConfiguration configuration, String path) {
        if(path == null)
            return null;

        String localPath;
        if(isFileOf(path, WEBOS_APP_FOLDER)) {
            localPath = getLocalPath(WEBOS_APP_FOLDER, configuration, path, configuration.getAppFolder());
        } else if(isFileOf(path, WEBOS_SERVICE_FOLDER)) {
            localPath = getLocalPath(WEBOS_SERVICE_FOLDER, configuration, path, configuration.getSrvFolder());
        } else {
            return null;
        }
        return LocalFileSystem.getInstance().findFileByPath(localPath);
    }

    private static boolean isFileOf(String path, VirtualFile folder) {
        return path.startsWith(folder.getUrl());
    }
    
    private static boolean isFileOf(String path, String folder) {
        return path.startsWith(folder);
    }
    
    private static String getWebOSPath(String webOSBasePath, WebOSRunConfiguration runConfiguration,
                                       String path, VirtualFile folder) {
        return webOSBasePath + runConfiguration.getAppId() + "/" +
                path.substring(folder.getUrl().length() + 1, path.length());
    }
    
    private static String getLocalPath(String webOSBasePath, WebOSRunConfiguration runConfiguration,
                                       String path, VirtualFile folder) {
        return folder.getPath() +
        path.substring(webOSBasePath.length() + runConfiguration.getAppId().length(), path.length());
    }
}
